package edu.chl.tdaniel.ws2;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import edu.chl.tdaniel.ws2.core.Product;
import edu.chl.tdaniel.ws2.db.Database;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * FrontController servlet
 * responsible for updating the model and navigating
 * (possibly depending on outcome of update)
 * @author Mikey
 */
@WebServlet(name = "FrontControllerServlet", urlPatterns = {"/FrontController"})
public class FrontControllerServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String action = request.getParameter("action");
        
        // shop: Get the products from database, put in request, navigate to shop.jspx
        if (action.equals("shop")){
           request.setAttribute("products", Database.getProducts());
           request.getRequestDispatcher("WEB-INF/jsp/shop.jspx").forward(request, response);
        }
        
        else if (action.equals("addProduct")){
            
            Product product = Database.getProduct(request.getParameter("product"));
            ShoppingCart cart = (ShoppingCart) request.getSession().getAttribute("cart");
            
            if(cart == null){
                cart = new ShoppingCart();  
                request.getSession().setAttribute("cart", cart);  
            }
            
            cart.addProduct(product);           
            response.sendRedirect("FrontController?action=shop");
        }
        
        else if (action.equals("removeProduct")){
            ShoppingCart cart = (ShoppingCart) request.getSession().getAttribute("cart");
            String product = request.getParameter("product"); 
            
            cart.removeProduct(product);

            request.getRequestDispatcher("WEB-INF/jsp/viewCart.jspx").forward(request, response);
        }
        
        else if (action.equals("pay")){          
            request.getRequestDispatcher("WEB-INF/jsp/pay.jspx").forward(request, response);
        }
        
               else if (action.equals("confirm")){
            // Retrieve cart and get content as a string
            ShoppingCart cart = (ShoppingCart) request.getSession().getAttribute("cart");
            if (cart != null && !cart.getRows().isEmpty()) {
                String cartString = cart.toString();

                //Send confirmation mail with content.
                try {
                    Mailer ma = new Mailer();
                    ma.sendConfirmation(cartString);
                }
                catch (Exception e) {
                    System.out.println("Error executing mailer");
                    e.printStackTrace();
                }

                //Removes cart from session.
                request.getSession().removeAttribute("cart");            

                //Navigats to confirm.jspx.
                request.getRequestDispatcher("WEB-INF/jsp/confirm.jspx").forward(request, response);
            }
            else {
                request.setAttribute("msg", "Your cart is empty, no payment necessary.");
                request.getRequestDispatcher("WEB-INF/jsp/pay.jspx").forward(request, response);                
            }
        }

        
        else if (action.equals("cart")) {
            request.getRequestDispatcher("WEB-INF/jsp/viewCart.jspx").forward(request, response);
        }
        
        
        
        
        
        
        //response.setContentType("text/html;charset=UTF-8");
        /*
        HttpSession s = request.getSession();
        
        if (s.getAttribute("user") == null) {
            response.sendRedirect("main.jspx");
        }
        else
        {
            //shop
            //cart
            //pay
            this.getServletContext().getResourceAsStream("WEB-INF/jsp/shop.jspx");
            */
            /*
            PrintWriter out = response.getWriter();
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet FrontControllerServlet</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet FrontControllerServlet at " + request.getParameter("action") + "</h1>");
            out.println("</body>");
            out.println("</html>");
            // do something
             */
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
